<template>
  <el-card class="notification-card" :body-style="{ padding: '0' }">
    <template #header>
      <div class="card-header">
        <div class="header-title">
          <i class="el-icon-bell mr-2"></i>
          <span class="text-xl font-semibold">通知中心</span>
        </div>
        <div class="header-actions">
          <el-button
            v-if="userInfo.role === 'teacher'"
            type="primary"
            size="small"
            class="create-btn"
            @click="showCreateDialog"
          >
            <i class="el-icon-plus mr-1"></i>
            发布通知
          </el-button>
        </div>
      </div>
    </template>

    <div class="notification-filters">
      <el-radio-group v-model="filterType" size="small" @change="handleFilterChange">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="unread">未读</el-radio-button>
      </el-radio-group>
    </div>

    <el-table
      v-loading="loading"
      :data="notifications"
      style="width: 100%"
      class="custom-table"
    >
      <el-table-column prop="content" label="通知内容">
        <template #default="{ row }">
          <div
            class="notification-item"
            :class="{ 'unread': !row.is_read }"
            @click="showNotificationDetail(row)"
          >
            <div class="notification-main">
              <el-badge v-if="!row.is_read" is-dot class="notification-badge" />
              <span class="notification-text">{{ row.content }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          <el-tag
            :type="row.type === 'course' ? 'success' : 'info'"
            size="small"
            effect="light"
          >
            {{ row.type === 'course' ? '课程通知' : '提醒' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="时间" width="180">
        <template #default="{ row }">
          <span class="time-text">{{ formatDate(row.created_at) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建通知对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="发布新通知"
      width="550px"
      custom-class="custom-dialog"
      @close="closeCreateDialog"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="computedRules"
        label-width="90px"
        class="create-form"
      >
        <el-form-item label="发送至" prop="sendType">
          <el-radio-group v-model="createForm.sendType" class="send-type-group">
            <el-radio label="course">
              <i class="el-icon-reading mr-1"></i>课程学生
            </el-radio>
            <el-radio label="user">
              <i class="el-icon-user mr-1"></i>指定用户
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="createForm.sendType === 'course'"
          label="选择课程"
          prop="course_id"
        >
          <el-select
            v-model="createForm.course_id"
            placeholder="请选择课程"
            clearable
            class="w-full"
          >
            <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="createForm.sendType === 'user'"
          label="用户ID"
          prop="user_id"
        >
          <el-input
            v-model="createForm.user_id"
            placeholder="请输入用户ID"
            clearable
          >
          </el-input>
        </el-form-item>

        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="createForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入通知内容"
            class="content-input"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeCreateDialog">取消</el-button>
          <el-button
            type="primary"
            @click="submitNotification"
            :loading="submitting"
          >
            发布通知
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 通知详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="通知详情"
      width="550px"
      custom-class="custom-dialog detail-dialog"
    >
      <div v-if="currentNotification" class="notification-detail">
        <div class="detail-header">
          <el-tag
            :type="currentNotification.type === 'course' ? 'success' : 'info'"
            size="small"
            effect="light"
          >
            {{ currentNotification.type === 'course' ? '课程通知' : '提醒' }}
          </el-tag>
          <span class="detail-time">
            {{ formatDate(currentNotification.created_at) }}
          </span>
        </div>
        <p class="detail-content">{{ currentNotification.content }}</p>
        <div class="detail-footer">
          <div class="sender-info" v-if="currentNotification.user">
            <span class="sender-name">{{ currentNotification.user.username }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { ref, computed, onMounted} from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'NotificationList',
  props: {
    userInfo: {
      type: Object,
      required: true
    }
  },
  setup(props) {
    const notifications = ref([])
    const loading = ref(false)
    const unreadStats = ref({ total: 0, by_type: {} })
    const createDialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const currentNotification = ref(null)
    const submitting = ref(false)
    const courseList = ref([])
    const createFormRef = ref(null)
    const filterType = ref('all')


    const createForm = ref({
      sendType: 'course',
      course_id: '',
      user_id: '',
      content: '',
      type: 'course'
    })
    // 添加新的筛选处理函数
    const handleFilterChange = async (value) => {
      if (value === 'unread') {
        await fetchUnreadNotifications()
      } else {
        await fetchNotifications()
      }
    }

    const computedRules = computed(() => {
      const baseRules = {
        content: [
          { required: true, message: '请输入通知内容', trigger: 'blur' }
        ],
        sendType: [
          { required: true, message: '请选择发送类型', trigger: 'change' }
        ]
      }

      if (createForm.value.sendType === 'course') {
        baseRules.course_id = [
          { required: true, message: '请选择课程', trigger: 'change' }
        ]
      } else {
        baseRules.user_id = [
          { required: true, message: '请输入用户ID', trigger: 'blur' }
        ]
      }

      return baseRules
    })

    const fetchCourseList = async () => {
      try {
        const response = await axios.post('/backend/api/course/courses/', {
          semester: getCurrentSemester() // 获取当前学期
        })
        courseList.value = response.data
      } catch (error) {
        ElMessage.error('获取课程列表失败')
        console.error('获取课程列表错误:', error)
      }
    }

    // 获取当前学期
    const getCurrentSemester = () => {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      // 上半年用1000，下半年用2000
      const term = month >= 2 && month <= 7 ? '1000' : '2000'
      return `${year}-${term}`
    }

    const fetchNotifications = async () => {
      try {
        loading.value = true
        const response = await axios.get('/backend/api/post/notifications/')
        notifications.value = response.data.notifications
        unreadStats.value = response.data.unread_stats
      } catch (error) {
        ElMessage.error('获取通知列表失败')
        console.error('获取通知列表错误:', error)
      } finally {
        loading.value = false
      }
    }
    //获取未读通知列表
    const fetchUnreadNotifications = async () => {
      try {
        loading.value = true
        const response = await axios.get('/backend/api/post/notifications/unread/')
        notifications.value = response.data.notifications
        unreadStats.value = response.data.unread_stats
      } catch (error) {
        ElMessage.error('获取未读通知失败')
        console.error('获取未读通知错误:', error)
      } finally {
        loading.value = false
      }
    }
  //  获取通知详情
    const showNotificationDetail = async (notification) => {
      try {
        // 1. 获取通知详情
        const detailResponse = await axios.get(`/backend/api/post/notifications/${notification.id}/`)
        currentNotification.value = detailResponse.data
        detailDialogVisible.value = true

        // 2. 如果通知未读，则标记为已读
        if (!notification.is_read) {
          await markNotificationAsRead(notification.id)

          // 3. 更新本地通知列表中的已读状态
          const index = notifications.value.findIndex(n => n.id === notification.id)
          if (index !== -1) {
            notifications.value[index].is_read = true
          }

          // 4. 更新未读统计
          updateUnreadStats()
        }
      } catch (error) {
        ElMessage.error('获取通知详情失败')
        console.error('获取通知详情错误:', error)
      }
    }

    // 添加标记已读的方法
    const markNotificationAsRead = async (notificationId) => {
      try {
        await axios.post(`/backend/api/post/notifications/${notificationId}/read/`)
      } catch (error) {
        console.error('标记通知已读失败:', error)
      }
    }

    // 更新未读统计的方法
    const updateUnreadStats = () => {
      // 更新总未读数
      unreadStats.value.total = Math.max(0, unreadStats.value.total - 1)

      // 更新分类未读数
      if (unreadStats.value.by_type.course > 0) {
        unreadStats.value.by_type.course -= 1
      }
    }

    const resetCreateForm = () => {
      createForm.value = {
        sendType: 'course',
        course_id: '',
        user_id: '',
        content: '',
        type: 'course'
      }
      if (createFormRef.value) {
        createFormRef.value.resetFields()
      }
    }

    const closeCreateDialog = () => {
      createDialogVisible.value = false
      resetCreateForm()
    }

    const showCreateDialog = () => {
      resetCreateForm()
      createDialogVisible.value = true
    }

    const submitNotification = async () => {
      if (!createFormRef.value) return

      await createFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            submitting.value = true
            const requestData = {
              content: createForm.value.content,
              type: 'course'
            }

            if (createForm.value.sendType === 'course') {
              requestData.course_id = createForm.value.course_id
            } else {
              requestData.user_id = createForm.value.user_id
            }

            await axios.post('/backend/api/post/notifications/create/', requestData)
            ElMessage.success('通知发布成功')
            closeCreateDialog()
            fetchNotifications()
          } catch (error) {
            ElMessage.error('通知发布失败')
            console.error('发布通知错误:', error)
          } finally {
            submitting.value = false
          }
        }
      })
    }

    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    onMounted(() => {
      fetchNotifications()
      // 如果是教师用户，获取课程列表
      if (props.userInfo.role === 'teacher') {
        fetchCourseList()
      }
    })

    return {
      notifications,
      loading,
      unreadStats,
      createDialogVisible,
      detailDialogVisible,
      currentNotification,
      createForm,
      createFormRef,
      computedRules,
      courseList,
      submitting,
      showCreateDialog,
      handleFilterChange,
      closeCreateDialog,
      submitNotification,
      fetchNotifications,
      fetchUnreadNotifications,
      showNotificationDetail,
      formatDate
    }
  }
}
</script>

<style scoped>
.notification-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.notification-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.header-title {
  display: flex;
  align-items: center;
  color: #303133;
}


.header-actions {
  display: flex;
  gap: 12px;
}

.create-btn {
  transition: all 0.3s ease;
}

.create-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.notification-filters {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.custom-table {
  background-color: transparent;
}

.notification-item {
  padding: 12px 0;
  cursor: pointer;
  transition: all 0.3s ease;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #f0f9ff;
}

.notification-main {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}
.notification-text {
  color: #303133;
  line-height: 1.6;
}

.time-text {
  color: #909399;
  font-size: 13px;
}
.create-form {
  padding: 20px 0;
}

.send-type-group {
  display: flex;
  gap: 24px;
}

.content-input :deep(.el-textarea__inner) {
  border-radius: 4px;
  padding: 12px;
  line-height: 1.6;
}

.notification-detail {
  padding: 24px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.detail-time {
  color: #909399;
  font-size: 13px;
}

.detail-content {
  font-size: 15px;
  line-height: 1.8;
  color: #303133;
  margin: 20px 0;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.detail-footer {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.sender-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.sender-name {
  color: #606266;
  font-size: 14px;
}

/* Element Plus 组件样式覆盖 */

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.notification-item {
  animation: fadeIn 0.3s ease-out;
}
</style>